package com.siro.pm.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.siro.pm.utils.DatabaseOperation;
import com.siro.pm.utils.DatabasePool;

/**
 * Class Declaration:
 * 
 * @version v1.0
 * @since Project.java v1.0
 */
public class Project implements Serializable {
	private static final long serialVersionUID = -8425786215658611244L;

	private static final Logger logger = LoggerFactory.getLogger(Project.class);
	// id, 项目名称，项目经理，合作方负责人，开发人员，项目状态，项目进度，相关文档，需求/BUG, 开始时间，预计完成时间
	private String id;
	private String name;
	private Developer manager;
	private Developer partnerLeader;
	private String status;
	private String process;
	private String startTime;
	private String estimatedEndTime;

	private List<Developer> developers;
	private List<Document> docs;
	private List<DemandOrBug> demandsOrBugs;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Developer getManager() {
		return manager;
	}

	public void setManager(Developer manager) {
		this.manager = manager;
	}

	public Developer getPartnerLeader() {
		return partnerLeader;
	}

	public void setPartnerLeader(Developer partnerLeader) {
		this.partnerLeader = partnerLeader;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public String getProcess() {
		return process;
	}

	public void setProcess(String process) {
		this.process = process;
	}

	public String getStartTime() {
		return startTime;
	}

	public void setStartTime(String startTime) {
		this.startTime = startTime;
	}

	public String getEstimatedEndTime() {
		return estimatedEndTime;
	}

	public void setEstimatedEndTime(String estimatedEndTime) {
		this.estimatedEndTime = estimatedEndTime;
	}

	public List<Developer> getDevelopers() {
//		if (developers != null && developers.isEmpty()) {
//			developers.addAll(Developer.getDevelopers(this));
//		}
//		return developers;
		return Developer.getDevelopers(this);
	}

	public void setDevelopers(List<Developer> developers) {
		this.developers = developers;
	}

	public void addDeveloper(Developer developer) {
		developers.add(developer);
	}

	public List<Document> getDocs() {
//		if (docs != null && docs.isEmpty()) {
//			docs.addAll(Document.getDocuments(this));
//		}
//		return docs;
		return Document.getDocuments(this);
	}

	public void setDocs(List<Document> docs) {
		this.docs = docs;
	}

	public void addDoc(Document document) {
		docs.add(document);
	}

	public List<DemandOrBug> getDemandsOrBugs() {
//		if (demandsOrBugs != null && demandsOrBugs.isEmpty()) {
//			demandsOrBugs.addAll(DemandOrBug.getDemandOrBugs(this));
//		}
//		return demandsOrBugs;
		return DemandOrBug.getDemandOrBugs(this);
	}

	public void setDemandsOrBugs(List<DemandOrBug> demandsOrBugs) {
		this.demandsOrBugs = demandsOrBugs;
	}

	public void addDemandsOrBug(DemandOrBug demandsOrBug) {
		demandsOrBugs.add(demandsOrBug);
	}

	public boolean equals(Object anObject) {
		if (anObject instanceof Project) {
			return this.getId().equals(((Project) anObject).getId());
		} else {
			return false;
		}
	}

	public int hashCode() {
		return getId().hashCode();
	}

	public static void insertProject(Project project) {
		logger.info("添加工程，id:{},name:{}", project.getId(), project.getName());
		StringBuffer sql = new StringBuffer();
		sql.append("INSERT INTO siropm_project VALUES('");
		sql.append(project.getId()).append("','");
		sql.append(project.getName()).append("','");
		sql.append(project.getManager().getId()).append("','");
		sql.append(project.getPartnerLeader().getId()).append("','");
		sql.append(project.getStatus()).append("','");
		sql.append(project.getProcess()).append("','");
		sql.append(project.getStartTime()).append("','");
		sql.append(project.getEstimatedEndTime()).append("')");
		try {
			DatabaseOperation.excuteUpdateSQL(DatabasePool.getConnection(),
					sql.toString());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		logger.info("添加工程，id:{},name:{} 成功", project.getId(), project.getName());
	}

	public static void deleteProject(Project project) {
		logger.info("删除工程，id:{},name:{}", project.getId(), project.getName());
		String sql = "DELETE FROM siropm_project WHERE id='" + project.getId()
				+ "'";
		try {
			DatabaseOperation
					.excuteUpdateSQL(DatabasePool.getConnection(), sql);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		logger.info("删除工程，id:{},name:{} 成功", project.getId(), project.getName());
	}

	public static void updateProject(Project project) {
		logger.info("更新工程，id:{} name:{}", project.getId(), project.getName());
		StringBuffer sql = new StringBuffer();
		sql.append("UPDATE siropm_project SET ");
		sql.append("name='").append(project.getName()).append("', ");
		sql.append("manager='").append(project.getManager().getId())
				.append("', ");
		sql.append("partnerLeader='")
				.append(project.getPartnerLeader().getId()).append("',");
		sql.append("status='").append(project.getStatus()).append("',");
		sql.append("process='").append(project.getProcess()).append("',");
		sql.append("startTime='").append(project.getStartTime()).append("',");
		sql.append("estimatedEndTime='").append(project.getEstimatedEndTime())
				.append("'");
		sql.append("WHERE id='").append(project.getId()).append("'");
		try {
			DatabaseOperation.excuteUpdateSQL(DatabasePool.getConnection(),
					sql.toString());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		logger.info("更新工程，id:{} name:{} 成功", project.getId(), project.getName());
	}

	public static List<Project> getAllProjects() {
		logger.info("获取所有工程...");
		List<Project> projects = new ArrayList<Project>();
		String sql = "SELECT id,name,manager,partnerLeader,status,process,startTime,estimatedEndTime FROM siropm_project";
		try {
			Map<Integer, List<String>> rslt = DatabaseOperation
					.excuteSelectSQL(DatabasePool.getConnection(), sql);
			List<String> row = null;
			for (int i = 1; i <= rslt.size(); i++) {
				row = rslt.get(i);
				Project project = new Project();
				project.setId(row.get(0));
				project.setName(row.get(1));
				project.setManager(Developer.getDeveloper(row.get(2)));
				if (row.get(3) != null && !row.get(3).equals(""))
					project.setPartnerLeader(Developer.getDeveloper(row.get(3)));
				if (row.get(4) != null && !row.get(4).equals(""))
					project.setStatus(row.get(4));
				if (row.get(5) != null && !row.get(5).equals(""))
					project.setProcess(row.get(5));
				if (row.get(6) != null && !row.get(6).equals(""))
					project.setStartTime(row.get(6));
				if (row.get(7) != null && !row.get(7).equals(""))
					project.setEstimatedEndTime(row.get(7));
				project.setDevelopers(Developer.getDevelopers(project));
				project.setDemandsOrBugs(DemandOrBug.getDemandOrBugs(project));
				project.setDocs(Document.getDocuments(project));
				projects.add(project);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return projects;
	}

	public static Project getProject(String id) {
		logger.info("获取工程,ID:" + id);
		Project project = null;
		String sql = "SELECT id,name,manager,partnerLeader,status,process,startTime,estimatedEndTime FROM siropm_project WHERE id='"
				+ id + "'";
		try {
			Map<Integer, List<String>> rslt = DatabaseOperation
					.excuteSelectSQL(DatabasePool.getConnection(), sql);
			if (rslt == null || rslt.size() == 0)
				return null;
			List<String> row = rslt.get(1);
			project = new Project();
			project.setId(row.get(0));
			project.setName(row.get(1));
			project.setManager(Developer.getDeveloper(row.get(2)));
			if (row.get(3) != null && !row.get(3).equals(""))
				project.setPartnerLeader(Developer.getDeveloper(row.get(3)));
			if (row.get(4) != null && !row.get(4).equals(""))
				project.setStatus(row.get(4));
			if (row.get(5) != null && !row.get(5).equals(""))
				project.setProcess(row.get(5));
			if (row.get(6) != null && !row.get(6).equals(""))
				project.setStartTime(row.get(6));
			if (row.get(7) != null && !row.get(7).equals(""))
				project.setEstimatedEndTime(row.get(7));
			project.setDevelopers(Developer.getDevelopers(project));
			project.setDemandsOrBugs(DemandOrBug.getDemandOrBugs(project));
			project.setDocs(Document.getDocuments(project));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return project;
	}

	public static List<Project> getProjects(Developer developer) {
		logger.info("获取用户：{} 相关的所有工程", developer.getName());
		List<Project> projects = new ArrayList<Project>();
		Set<Project> projectsSet = new HashSet<Project>();
		String sql = "SELECT projectid,developerid FROM siropm_project_developer WHERE developerid ='"
				+ developer.getId() + "'";
		try {
			Map<Integer, List<String>> rslt = DatabaseOperation
					.excuteSelectSQL(DatabasePool.getConnection(), sql);
			List<String> row = null;
			for (int i = 1; i <= rslt.size(); i++) {
				row = rslt.get(i);
				Project project = getProject(row.get(0));
				project.setDevelopers(Developer.getDevelopers(project));
				project.setDemandsOrBugs(DemandOrBug.getDemandOrBugs(project));
				project.setDocs(Document.getDocuments(project));
				projectsSet.add(project);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		// manager or partner leader
		sql = "SELECT id,name,manager,partnerLeader,status,process,startTime,estimatedEndTime FROM siropm_project  WHERE manager='"
				+ developer.getId()
				+ "' OR partnerLeader='"
				+ developer.getId() + "'";
		try {
			Map<Integer, List<String>> rslt = DatabaseOperation
					.excuteSelectSQL(DatabasePool.getConnection(), sql);
			List<String> row = null;
			for (int i = 1; i <= rslt.size(); i++) {
				row = rslt.get(i);
				Project project = new Project();
				project.setId(row.get(0));
				project.setName(row.get(1));
				project.setManager(Developer.getDeveloper(row.get(2)));
				if (row.get(3) != null && !row.get(3).equals(""))
					project.setPartnerLeader(Developer.getDeveloper(row.get(3)));
				if (row.get(4) != null && !row.get(4).equals(""))
					project.setStatus(row.get(4));
				if (row.get(5) != null && !row.get(5).equals(""))
					project.setProcess(row.get(5));
				if (row.get(6) != null && !row.get(6).equals(""))
					project.setStartTime(row.get(6));
				if (row.get(7) != null && !row.get(7).equals(""))
					project.setEstimatedEndTime(row.get(7));
				project.setDevelopers(Developer.getDevelopers(project));
				project.setDemandsOrBugs(DemandOrBug.getDemandOrBugs(project));
				project.setDocs(Document.getDocuments(project));
				projectsSet.add(project);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		projects.addAll(projectsSet);
		return projects;
	}

	public static void addDeveloper(Project ownerProject, Developer developer) {
		logger.info("为工程，name:{} 添加开发人员：{}", ownerProject.getName(),
				developer.getName());
		StringBuffer sql = new StringBuffer();
		sql.append("INSERT INTO siropm_project_developer VALUES('");
		sql.append(ownerProject.getId()).append("','");
		sql.append(developer.getId()).append("')");
		try {
			DatabaseOperation.excuteUpdateSQL(DatabasePool.getConnection(),
					sql.toString());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		logger.info("为工程，name:{} 添加开发人员：{} 成功", ownerProject.getName(),
				developer.getName());
	}

	public static void deleteDeveloper(Project ownerProject, Developer developer) {
		logger.info("为工程，name:{} 删除开发人员：{}", ownerProject.getName(),
				developer.getName());
		String sql = "DELETE FROM siropm_project_developer WHERE projectid='"
				+ ownerProject.getId() + "' AND developerid ='"
				+ developer.getId() + "'";
		try {
			DatabaseOperation
					.excuteUpdateSQL(DatabasePool.getConnection(), sql);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		logger.info("为工程，name:{} 删除开发人员：{} 成功", ownerProject.getName(),
				developer.getName());
	}

}
